package com.mylogistics.common.controller;


import com.mylogistics.common.vo.ResultData;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * 反应validation错误信息
 */
@RestControllerAdvice
public class ValidationHandler {
    //用于抓取validation产生的错误
    @ExceptionHandler(BindException.class)
    public ResultData exceptionHandler(BindException e){
        ResultData rd  = new ResultData();
        rd.setCode(40000);
        List<FieldError> list = e.getFieldErrors();
        List<String> listError = new ArrayList<>();
        for (FieldError fieldError :list) {
            listError.add(fieldError.getDefaultMessage());
        }
        rd.setData(listError);
        return rd;
    }
}